/*
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package jchess;

import org.jdesktop.application.Action;
import org.jdesktop.application.Application;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
import java.io.File;
import java.applet.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import javax.swing.filechooser.FileFilter;

/**
 * The application's main frame.
 */
public class JChessView extends FrameView implements ActionListener, ComponentListener {
    //tak raczej nie powinno być :/

    static GUI gui = null;
    GUI activeGUI;//in future it will be reference to active tab

    public JChessView(GUI activeGUI, JButton jButton1, JButton jButtonAbrirAuxiliar, JButton jButtonAvancar, JButton jButtonVoltar, JTabbedPane jTabbedPane1, JMenuItem loadGameItem, JPanel mainPanel, JMenuBar menuBar, JMenuItem newGameItem, JMenu optionsMenu, JProgressBar progressBar, JMenuItem saveGameItem, JLabel statusAnimationLabel, JLabel statusMessageLabel, JPanel statusPanel, JMenuItem themeSettingsMenu, Timer messageTimer, Timer busyIconTimer, Icon idleIcon, JDialog aboutBox, PawnPromotionWindow promotionBox, JDialog newGameFrame, Application application) {
        super(application);
        this.activeGUI = activeGUI;
        this.jButton1 = jButton1;
        this.jButtonAbrirAuxiliar = jButtonAbrirAuxiliar;
        this.jButtonAvancar = jButtonAvancar;
        this.jButtonVoltar = jButtonVoltar;
        this.jTabbedPane1 = jTabbedPane1;
        this.loadGameItem = loadGameItem;
        this.mainPanel = mainPanel;
        this.menuBar = menuBar;
        this.newGameItem = newGameItem;
        this.optionsMenu = optionsMenu;
        this.progressBar = progressBar;
        this.saveGameItem = saveGameItem;
        this.statusAnimationLabel = statusAnimationLabel;
        this.statusMessageLabel = statusMessageLabel;
        this.statusPanel = statusPanel;
        this.themeSettingsMenu = themeSettingsMenu;
        this.messageTimer = messageTimer;
        this.busyIconTimer = busyIconTimer;
        this.idleIcon = idleIcon;
        this.aboutBox = aboutBox;
        this.promotionBox = promotionBox;
        this.newGameFrame = newGameFrame;
    }

    public Game addNewTab(String title) {
        Game newGUI = new Game();
        this.jTabbedPane1.addTab(title, newGUI);
        return newGUI;
    }

    public void actionPerformed(ActionEvent event) {
        Object target = event.getSource();
        if (target == newGameItem) {
            this.newGameFrame = new NewGameWindow();
            JChessApp.getApplication().show(this.newGameFrame);
        } else if (target == saveGameItem) { //saveGame
            if (this.jTabbedPane1.getTabCount() == 0) {
                JOptionPane.showMessageDialog(null, Settings.lang("save_not_called_for_tab"));
                return;
            }
            System.out.println("hello");
            while (true) {//until
                JFileChooser fc = new JFileChooser();
                int retVal = fc.showSaveDialog(this.jTabbedPane1);
                if (retVal == JFileChooser.APPROVE_OPTION) {
                    File selFile = fc.getSelectedFile();
                    if (!selFile.getName().endsWith(".pgn")) {
                        selFile = new File(selFile.getAbsoluteFile() + ".pgn");
                    }
                    Game tempGUI = (Game) this.jTabbedPane1.getComponentAt(this.jTabbedPane1.getSelectedIndex());
                    if (!selFile.exists()) {
                        try {
                            selFile.createNewFile();
                        } catch (java.io.IOException exc) {
                            System.out.println("error creating file: " + exc);
                        }
                    } else if (selFile.exists()) {
                        int opt = JOptionPane.showConfirmDialog(tempGUI, Settings.lang("file_exists"), Settings.lang("file_exists"), JOptionPane.YES_NO_OPTION);
                        if (opt == JOptionPane.NO_OPTION) {//if user choose to now overwrite
                            continue; // go back to file choose
                        }
                    }
                    if (selFile.canWrite()) {
                        tempGUI.saveGame(selFile, true, true);
                    }
                    System.out.println(fc.getSelectedFile().isFile());
                    break;
                } else if (retVal == JFileChooser.CANCEL_OPTION) {
                    break;
                }
                ///JChessView.gui.game.saveGame(fc.);
            }
        } else if (target == loadGameItem) { //loadGame
            JFileChooser fc = new JFileChooser();
            fc.addChoosableFileFilter(new FileFilter() {

                @Override
                public boolean accept(File f) {
                    if (f.isDirectory() || (f.canRead() && f.getName().endsWith(".pgn"))) {
                        return true;
                    }
                    return false;
                }

                @Override
                public String getDescription() {
                    return "*.PGN full chess notation files";
                }
            });
            int retVal = fc.showOpenDialog(this.jTabbedPane1);
            if (retVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                if (file.exists() && file.canRead()) {
                    Game.loadGame(file);
                }
            }
        } else if (target == this.themeSettingsMenu) {
            JChessApp.getApplication().show(new ThemeChooseWindow(this.getFrame()));
        }
    }

    ///--endOf- don't delete, becouse they're interfaces for MouseEvent
    public JChessView(SingleFrameApplication app) {
        super(app);

        initComponents();
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });

    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = JChessApp.getApplication().getMainFrame();
            aboutBox = new JChessAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        JChessApp.getApplication().show(aboutBox);
    }

    public String showPawnPromotionBox(String color) {
        if (promotionBox == null) {
            JFrame mainFrame = JChessApp.getApplication().getMainFrame();
            promotionBox = new PawnPromotionWindow(mainFrame, color);
            promotionBox.setLocationRelativeTo(mainFrame);
            promotionBox.setModal(true);

        }
        promotionBox.setColor(color);
        JChessApp.getApplication().show(promotionBox);

        return promotionBox.result;
    }

    public String showSaveWindow() {

        return "";
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jTabbedPane1 = new jchess.JChessTabbedPane();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        newGameItem = new javax.swing.JMenuItem();
        loadGameItem = new javax.swing.JMenuItem();
        saveGameItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        optionsMenu = new javax.swing.JMenu();
        themeSettingsMenu = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        jButtonAbrirAuxiliar = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButtonAvancar = new javax.swing.JButton();
        jButtonVoltar = new javax.swing.JButton();

        mainPanel.setMaximumSize(new java.awt.Dimension(800, 600));
        mainPanel.setMinimumSize(new java.awt.Dimension(800, 600));
        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setPreferredSize(new java.awt.Dimension(800, 600));

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 774, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(18, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap(66, Short.MAX_VALUE)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 570, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        menuBar.setName("menuBar"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(jchess.JChessApp.class).getContext().getResourceMap(JChessView.class);
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        newGameItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        newGameItem.setText(resourceMap.getString("newGameItem.text")); // NOI18N
        newGameItem.setName("newGameItem"); // NOI18N
        fileMenu.add(newGameItem);
        newGameItem.addActionListener(this);

        loadGameItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK));
        loadGameItem.setText(resourceMap.getString("loadGameItem.text")); // NOI18N
        loadGameItem.setName("loadGameItem"); // NOI18N
        fileMenu.add(loadGameItem);
        loadGameItem.addActionListener(this);

        saveGameItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        saveGameItem.setText(resourceMap.getString("saveGameItem.text")); // NOI18N
        saveGameItem.setName("saveGameItem"); // NOI18N
        fileMenu.add(saveGameItem);
        saveGameItem.addActionListener(this);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(jchess.JChessApp.class).getContext().getActionMap(JChessView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        optionsMenu.setText(resourceMap.getString("optionsMenu.text")); // NOI18N
        optionsMenu.setName("optionsMenu"); // NOI18N

        themeSettingsMenu.setText(resourceMap.getString("themeSettingsMenu.text")); // NOI18N
        themeSettingsMenu.setName("themeSettingsMenu"); // NOI18N
        optionsMenu.add(themeSettingsMenu);
        themeSettingsMenu.addActionListener(this);

        menuBar.add(optionsMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        jButtonAbrirAuxiliar.setText(resourceMap.getString("jButtonAbrirAuxiliar.text")); // NOI18N
        jButtonAbrirAuxiliar.setName("jButtonAbrirAuxiliar"); // NOI18N
        jButtonAbrirAuxiliar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAbrirAuxiliarActionPerformed(evt);
            }
        });

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButtonAvancar.setText(resourceMap.getString("jButtonAvancar.text")); // NOI18N
        jButtonAvancar.setName("jButtonAvancar"); // NOI18N
        jButtonAvancar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAvancarActionPerformed(evt);
            }
        });

        jButtonVoltar.setText(resourceMap.getString("jButtonVoltar.text")); // NOI18N
        jButtonVoltar.setName("jButtonVoltar"); // NOI18N
        jButtonVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonVoltarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonAbrirAuxiliar)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(statusPanelLayout.createSequentialGroup()
                        .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(statusPanelLayout.createSequentialGroup()
                                .addGap(124, 124, 124)
                                .addComponent(statusMessageLabel)
                                .addGap(170, 170, 170))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButtonVoltar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonAvancar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1)
                                .addGap(103, 103, 103)))
                        .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(statusPanelLayout.createSequentialGroup()
                                .addGap(117, 117, 117)
                                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup()
                                .addComponent(statusAnimationLabel)
                                .addContainerGap())))
                    .addGroup(statusPanelLayout.createSequentialGroup()
                        .addGap(462, 462, 462)
                        .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(29, 29, 29))))
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(statusMessageLabel)
                        .addComponent(statusAnimationLabel))
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAbrirAuxiliar)
                    .addComponent(jButton1)
                    .addComponent(jButtonAvancar)
                    .addComponent(jButtonVoltar))
                .addContainerGap())
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

private void jButtonAbrirAuxiliarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAbrirAuxiliarActionPerformed
// TODO add your handling code here:
    int indexTab = 0;
    String tituloTab = null;

    indexTab = this.jTabbedPane1.getSelectedIndex();
    tituloTab = this.jTabbedPane1.getTitleAt(indexTab);

    if (!tituloTab.contains("Tab. Auxiliar ")) {

        // Salvar temporariamente o jogo
        if (this.jTabbedPane1.getTabCount() == 0) {
            JOptionPane.showMessageDialog(null, "Não há nenhuma partida aberta.\n"
                    + "Inicie uma nova ou carregue uma a partir de um arquivo PGN.");
            return;
        }
        Game tempGUI = (Game) this.jTabbedPane1.getComponentAt(this.jTabbedPane1.getSelectedIndex());
        File arquivoTemporario = new File("analiseJogadaJoChess.pgn");
        try {
            arquivoTemporario.createNewFile();
        } catch (java.io.IOException exc) {
            System.out.println("error creating file: " + exc);
        }
        if (arquivoTemporario.canWrite()) {
            tempGUI.saveGame(arquivoTemporario, false, false);
        }

        // Abrir o jogo salvo no novo tabuleiro
        if (arquivoTemporario.exists() && arquivoTemporario.canRead()) {
            Game.loadGame(arquivoTemporario);
        }
        this.jButtonAvancar.setVisible(true);
        this.jButtonVoltar.setVisible(true);
        this.jButton1.setVisible(true);
        this.jButtonAvancar.setEnabled(false);
        jTabbedPane1.setSelectedIndex(indexTab + 1);
    } else {
        JOptionPane.showMessageDialog(null, "Já está em um Tabuleiro Auxiliar!");
        return;
    }
}//GEN-LAST:event_jButtonAbrirAuxiliarActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    int indexTab = 0;
    String tituloTab = null;

    indexTab = this.jTabbedPane1.getSelectedIndex();
    tituloTab = this.jTabbedPane1.getTitleAt(indexTab);

    if (tituloTab.contains("Tab. Auxiliar ")) {
        Game tempGUI = (Game) this.jTabbedPane1.getComponentAt(this.jTabbedPane1.getSelectedIndex());
        tempGUI.casasNeutras();
    } else {
        JOptionPane.showMessageDialog(null, "Disponível no Tabuleiro Auxiliar!");
        return;
    }
}//GEN-LAST:event_jButton1ActionPerformed

private void jButtonVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVoltarActionPerformed
// TODO add your handling code here:
    int numeroDeJogadas = 0;
    int indexTab = 0;
    String tempStr = null;
    ArrayList<String> arrayMovimentos;
    Game tempGUI = (Game) this.jTabbedPane1.getComponentAt(this.jTabbedPane1.getSelectedIndex());

    String tituloTab = null;

    indexTab = this.jTabbedPane1.getSelectedIndex();
    tituloTab = this.jTabbedPane1.getTitleAt(indexTab);

    if (tituloTab.contains("Tab. Auxiliar ")) {

        arrayMovimentos = tempGUI.moves.getMoves();
        numeroDeJogadas = arrayMovimentos.size();

        //Se o numero de jogadas na tela for igual a zero, está na primeira jogada, não pode voltar mais.
        if (numeroDeJogadas == 1) {
            jButtonVoltar.setEnabled(false);
        }
        jButtonAvancar.setEnabled(true);

        numeroDeJogadas = numeroDeJogadas - 1;

        //Remove a Tab.
        this.jTabbedPane1.removeTabAt(indexTab);

        //Abre o arquivo temporario para reconhecer as jogadas.
        File file = new File("analiseJogadaJoChess.pgn");
        FileReader fileR = null;
        try {
            fileR = new FileReader(file);
        } catch (java.io.IOException exc) {
            System.out.println("Something wrong reading file: " + exc);
            return;
        }
        Game.loadGamePersonalizado(file, numeroDeJogadas);
        jTabbedPane1.setSelectedIndex(indexTab);

    } else {
        JOptionPane.showMessageDialog(null, "Disponível no Tabuleiro Auxiliar!");
        return;
    }
}//GEN-LAST:event_jButtonVoltarActionPerformed

private void jButtonAvancarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAvancarActionPerformed
// TODO add your handling code here:
    int numeroDeJogadas = 0;
    int numeroTotalDeJogadas = 0;
    int indexTab = 0;
    String tituloTab = null;
    String tempStr = null;
    String blackName, whiteName;
    ArrayList<String> arrayMovimentos;

    indexTab = this.jTabbedPane1.getSelectedIndex();
    tituloTab = this.jTabbedPane1.getTitleAt(indexTab);

    if (tituloTab.contains("Tab. Auxiliar ")) {

        Game tempGUI = (Game) this.jTabbedPane1.getComponentAt(this.jTabbedPane1.getSelectedIndex());

        arrayMovimentos = tempGUI.moves.getMoves();
        numeroDeJogadas = arrayMovimentos.size();
        numeroDeJogadas = numeroDeJogadas + 1;

        //Remove a Tab.
        this.jTabbedPane1.removeTabAt(indexTab);

        //Abre o arquivo temporario para reconhecer as jogadas.
        File file = new File("analiseJogadaJoChess.pgn");
        FileReader fileR = null;
        try {
            fileR = new FileReader(file);
        } catch (java.io.IOException exc) {
            System.out.println("Something wrong reading file: " + exc);
            return;
        }

        BufferedReader br = new BufferedReader(fileR);
        try {
            tempStr = Game.getLineWithVar(br, "[White");
            whiteName = Game.getValue(tempStr);
            tempStr = Game.getLineWithVar(br, "[Black");
            blackName = Game.getValue(tempStr);
            tempStr = Game.getLineWithVar(br, "1.");
        } catch (ReadGameError err) {
            System.out.println("Error reading file: " + err);
            return;
        }

        numeroTotalDeJogadas = tempGUI.moves.quantidadeDeJogadas(tempStr);

        if (numeroTotalDeJogadas == numeroDeJogadas) {
            jButtonAvancar.setEnabled(false);
        }

        jButtonVoltar.setEnabled(true);

        Game.loadGamePersonalizado(file, numeroDeJogadas);
        jTabbedPane1.setSelectedIndex(indexTab);

    } else {
        JOptionPane.showMessageDialog(null, "Disponível no Tabuleiro Auxiliar!");
        return;
    }
}//GEN-LAST:event_jButtonAvancarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonAbrirAuxiliar;
    private javax.swing.JButton jButtonAvancar;
    private javax.swing.JButton jButtonVoltar;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JMenuItem loadGameItem;
    public javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem newGameItem;
    private javax.swing.JMenu optionsMenu;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JMenuItem saveGameItem;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JMenuItem themeSettingsMenu;
    // End of variables declaration//GEN-END:variables
    //private JTabbedPaneWithIcon jTabbedPane1;
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
    private PawnPromotionWindow promotionBox;
    public JDialog newGameFrame;

    public void componentResized(ComponentEvent e) {
        System.out.println("jchessView resized!!;");
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void componentMoved(ComponentEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void componentShown(ComponentEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void componentHidden(ComponentEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
